package com.compty.paint.web.front;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.compty.core.framework.util.DateUtil;
import com.compty.core.framework.util.StringUtil;
import com.compty.core.struts2.BaseAction;
import com.compty.paint.domain.Bid;
import com.compty.paint.domain.BidRecord;
import com.compty.paint.domain.CustomerInfo;
import com.compty.paint.domain.Goods;
import com.compty.paint.domain.ImageInfo;
import com.compty.paint.domain.Painting;
import com.compty.paint.domain.support.BidClassificationByPainter;
import com.compty.paint.manager.BidManager;
import com.compty.paint.manager.BidRecordManager;
import com.compty.paint.util.Constants;

/**
 * @Todo:竟价拍卖Action
 * @CreateTime:2012-3-6 下午02:33:23
 */
public class BidAction  extends BaseAction<Bid> {

	private static final long serialVersionUID = -139391960322320544L;
	
	private BidRecordManager bidRecordManager;
	private BidManager bidManager;
	
	/**
	 *@Todo:对拍品加价,并记录加价信息
	 * @return
	 */
	public String bid(){
		
		CustomerInfo customerInfo = null;
		if(session.getAttribute(Constants.CustomerInfo) == null){
			return "login_bid";
		}else{
			customerInfo = (CustomerInfo) session.getAttribute(Constants.CustomerInfo);
		}
		
		String bid_id_str = request.getParameter("bid_id");
		if( !StringUtil.isDigit(bid_id_str) ){
			return ERROR;
		}
		Long  bid_Id = Long.valueOf(bid_id_str);
		
		String add_price_str = request.getParameter("add_price");//加价数额
		String current_price = request.getParameter("current_price");//当前价格
		if( !StringUtil.isNumber(add_price_str) || !StringUtil.isNumber(current_price) ){
			return ERROR;
		}
		String  flag = bidRecordManager.record(customerInfo,add_price_str,current_price,bid_Id);
		
		String returnMsg = "";
		if( flag == null){
			returnMsg = "缺少参数或参数错误";
		}
		else if("-1".equals(flag)){
			returnMsg = "拍品实时价格已更新,请重新加价。";
		}
		else if("1".equals(flag)){
			returnMsg = "加价成功";
		}
		else if("2".equals(flag)){
			returnMsg = "该拍品状态不正常，不能竟拍。";
		}
		else if("3".equals(flag)){
			returnMsg = "该拍品已结束竟拍，不能竟拍。";
		}
		else if("4".equals(flag)){
			returnMsg = "您的保证金不足，请先充值。";
		}
		
		request.setAttribute("returnMsg", returnMsg);
		
		String page_title = request.getParameter("page_title");
		String remain_time = request.getParameter("remain_time");
		
		request.setAttribute("page_title",page_title);
		request.setAttribute("remain_time",remain_time);
		
		return "bid";
	}
	
	/**
	 *@Todo:拍卖确认
	 *@CreateTime:2012-3-5 下午12:08:22
	 * @return
	 */
	public String bid_confirm(){
		
		if(session.getAttribute(Constants.CustomerInfo) == null){
			return "login_bid";
		}
		
		String bid_id_str = request.getParameter("bid_id");
		if( !StringUtil.isDigit(bid_id_str) ){
			return ERROR;
		}
		Long  bid_Id = Long.valueOf(bid_id_str);
		Bid bid = bidManager.findById(bid_Id);
//		String[] resultArray = checkCustomerLevelForBid(bid);
		String[] resultArray = {"true","ddd"};
		if("false".equals(resultArray[0])){
			request.setAttribute("returnMsg", "您参与竞拍的拍品底价为："+bid.getBeginPrice()+"元,需要保证金"+resultArray[1]+"元。您的保证金不足，请充值。");
			return "error";
		}
		if( bid == null ){
			
			request.setAttribute("returnMsg", "缺少参数或参数错误");
			
			String page_title = request.getParameter("page_title");
			String remain_time = request.getParameter("remain_time");
			
			request.setAttribute("page_title",page_title);
			request.setAttribute("remain_time",remain_time);
			
			return "error";
		}
		else{
			Integer bid_status = bid.getBid_status();
			Integer audit_status = bid.getAudit_status();
			if( audit_status != 2 || bid_status != 1){
				
				request.setAttribute("returnMsg", "该拍品状态不正常，不能竟拍");
				
				String page_title = request.getParameter("page_title");
				String remain_time = request.getParameter("remain_time");
				
				request.setAttribute("page_title",page_title);
				request.setAttribute("remain_time",remain_time);
				
				return "error";
			}else{
				Date endTime  = bid.getEndTime();
				if(Calendar.getInstance().getTime().compareTo(endTime)>0 ){
					
					request.setAttribute("returnMsg", "该拍品已结束竟拍，不能竟拍");
					
					String page_title = request.getParameter("page_title");
					String remain_time = request.getParameter("remain_time");
					
					request.setAttribute("page_title",page_title);
					request.setAttribute("remain_time",remain_time);
					
					return "error";
				}
			}
		}
		
		double currentPrice = 0;
		if( bid.getCurrentBidRecord() != null){
			currentPrice = bid.getCurrentBidRecord().getBidPrice();//当前价格
		}
		else{
			currentPrice = bid.getBeginPrice();
		}
		
		/************ 加价后的新价格 begin **************/
		String new_price_str = request.getParameter("new_price");
		if( !StringUtil.isNumber(new_price_str) ){
			return ERROR;
		}
		double new_price  = Double.valueOf(new_price_str);
		if(new_price <= currentPrice && new_price !=  bid.getBeginPrice()){
			request.setAttribute("returnMsg", "价钱不合法，请对拍品加价，再提交");
			
			String page_title = request.getParameter("page_title");
			String remain_time = request.getParameter("remain_time");
			request.setAttribute("page_title",page_title);
			request.setAttribute("remain_time",remain_time);
			
			return "error";
		}
		java.text.DecimalFormat   df   = new   java.text.DecimalFormat("#0.00");//保留两位小数 
		new_price_str = df.format(new_price);
		String add_price_str  = df.format(new_price  - currentPrice);
		/************ 加价后的新价格 end **************/
		
		request.setAttribute("bid", bid);
		request.setAttribute("new_price", new_price_str);
		request.setAttribute("current_price", currentPrice);
		request.setAttribute("add_price", add_price_str);
		request.setAttribute("bid_id", bid_id_str);
		
		String page_title = request.getParameter("page_title");
		String remain_time = request.getParameter("remain_time");
		
		request.setAttribute("page_title",page_title);
		request.setAttribute("remain_time",remain_time);
		
		return "bid_confirm";
	}
	
	/***
	 * 拍卖展示页
	 */
	@SuppressWarnings("unchecked")
	public String list(){
		
		this.page = bidManager.queryBid_available_ClassificationByPainter(curPage,10);
		
		Object result = page.getResult();
		List<BidClassificationByPainter> bidClassificationByPainterList  = (List)result;
		
		String jsonArrayStr = "[";
		int size = bidClassificationByPainterList.size();
		int i = 0 ;
		for (BidClassificationByPainter bidClassificationByPainter : bidClassificationByPainterList) {
			
			List<Bid> newestBidList = bidClassificationByPainter.getNewestBidList();
			
			if( newestBidList != null){
				jsonArrayStr += "[";
				for (int j = 0;j < newestBidList.size();j++) {
					
					Bid bid = newestBidList.get(j);
					Goods goods = bid.getGoods();
					Painting painting = goods.getPainting();
					
					String imgPath = painting.getImageInfo().getId()+"_bid."+ painting.getImageInfo().getSuffix();
					Long paintingId = painting.getId();
					String painterName = painting.getPainter().getName();
					Long painterId = painting.getPainter().getId();
					String paintingTitle = painting.getTitle();
					String caiZhi = painting.getCaiZhi();
					double width =  painting.getWidth();
					double height = painting.getHight();
					String provider = painting.getProvider();
					ImageInfo zhengshu = painting.getZhengshu();
					long zhengshu_id = 0;
					String zhengshu_imgPath = "";
					if( zhengshu != null){
						zhengshu_id = zhengshu.getId();
						zhengshu_imgPath = zhengshu.getId()+"."+zhengshu.getSuffix();
					}
					
					String newFlag = bid.getNewFlag();
					Long id = bid.getId();
					double beginPrice = bid.getBeginPrice();
					int bid_status = bid.getBid_status();
					BidRecord bidRecord = bid.getCurrentBidRecord();
					double bidPrice = 0 ;
					long customerId = 0;
					String displayName = "";
					if( bidRecord != null){
						bidPrice = bidRecord.getBidPrice();
						customerId = bidRecord.getCustomerInfo().getId();
						displayName = bidRecord.getCustomerInfo().getDisplayName();
					}
					
					String endTime = "";
					endTime = DateUtil.toString(bid.getEndTime(), "MM/dd/yyyy HH:mm:ss");
					
					jsonArrayStr += "{paintingId:"+paintingId+",imgPath:\""+imgPath+"\",painterId:"+painterId+",painterName:\""+painterName+"\"" +
							",paintingTitle:\""+paintingTitle+"\",caiZhi:\""+caiZhi+"\",width:"+width+",height:"+height+",provider:\""+provider+"\"" +
							",zhengshu_id:"+zhengshu_id+",zhengshu_imgPath:\""+zhengshu_imgPath+"\",newFlag:\""+newFlag+"\",id:"+id+",beginPrice:"+beginPrice+"" +
							",bid_status:"+bid_status+",bidPrice:"+bidPrice+",customerId:"+customerId+",displayName:\""+displayName+"\",endTime:\""+endTime+"\"}";
					
					if( j < newestBidList.size()-1 ){
						jsonArrayStr += ",";
					}
				}
				
				jsonArrayStr += "]";
			}
			else{
				jsonArrayStr +="[]";
			}
			if( ++i < size){
				jsonArrayStr += ",";
			}
		}
		
		jsonArrayStr += "]";
		
		request.setAttribute("jsonArrayStr", jsonArrayStr);
		
		return "list";
	}
	
	/**
	 *@Todo:查询当前出价
	 *@CreateTime:2012-3-11 上午11:58:35
	 * @return
	 */
	public String queryCurrentBid(){
		
		String bid_id_str = request.getParameter("bid_id");
		if( !StringUtil.isDigit(bid_id_str) ){
			return ERROR;
		}
		Long  bid_Id = Long.valueOf(bid_id_str);
		Bid bid = bidManager.getById(bid_Id);
		
		String ajaxData = "";
		
		BidRecord bidRecord = bid.getCurrentBidRecord();
		if( bidRecord != null){
			
			Long id = bidRecord.getId();
			double bidPrice = bidRecord.getBidPrice();
			Long userId = bidRecord.getCustomerInfo().getId();
			String displayName = bidRecord.getCustomerInfo().getDisplayName();
			int count = bid.getBidCount();
			
			ajaxData = "{id:"+ id +",bidPrice:"+ bidPrice +",userId:"+ userId +",username:\""+ displayName +"\",count:+"+count+"}";
		}
		
		request.setAttribute("ajaxData", ajaxData);
		
		return "current_bid";
	}
	
	/**
	 * 检查用户是否有资格对此拍品加价
	 */
	@SuppressWarnings("unused")
	private String[] checkCustomerLevelForBid(Bid bid) {
		String[] resultArray = new String[2];
		CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Constants.CustomerInfo);
		
		String  remark = customerInfo.getRemark();
		if("super".equals(remark)){
			resultArray[0] = "true";
			return resultArray;
		}
		
		Double advance = customerInfo.getAdvance();
		BidRecord bidRecord = bid.getCurrentBidRecord();
		double beginPrice = 0;
		if( bidRecord != null){
			beginPrice = bidRecord.getBidPrice();
		}else{
			beginPrice = bid.getBeginPrice();
		}
		
		double limit_money = 0;
		if(beginPrice <= 500){
			limit_money = 0;
		}
		else if(beginPrice<=2500){
			limit_money = 500;
		}
		else if(beginPrice<=2500){
			limit_money = 500;
		}
		else if(beginPrice<=5000){
			limit_money = 1000;
		}
		else if(beginPrice<=10000){
			limit_money = 2000;
		}
		else if(beginPrice<=25000){
			limit_money = 5000;
		}
		
		if( advance != null && advance >= limit_money){
			resultArray[0] = "true";
			return resultArray;
		}else{
			resultArray[0] = "false";
			resultArray[1] = String.valueOf(limit_money);
			return resultArray;
		}
	}

	public void setBidRecordManager(BidRecordManager bidRecordManager) {
		this.bidRecordManager = bidRecordManager;
	}

	public void setBidManager(BidManager bidManager) {
		this.bidManager = bidManager;
	}
}
